package com.github.lzm320a99981e.autocoding.domain.condition;

import com.google.common.base.CaseFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 排序信息
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class Sorts extends ArrayList<Sort> {
   
	private static final long serialVersionUID = -1603443831005021962L;

	/**
     * 将 property 转换为 column
     */
    private Function<String, String> toColumnFunction = property -> CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, property);

    /**
     * 将 Sort 转换为 SQL
     */
    private Function<Sort, String> toSqlFunction = sort -> String.join(",", Arrays.asList(sort.getProperties()).stream().map(toColumnFunction).collect(Collectors.toList())) + " " + sort.getDirection().name();

    /**
     * 转换为SQL
     *
     * @return
     */
    public String toSql() {
        if (isEmpty()) {
            throw new RuntimeException("排序条目为空");
        }
        return String.join(", ", this.stream().map(toSqlFunction).collect(Collectors.toList()));
    }
}
